var h = $(window).height(),
    addList = [],
    w = $('.ul-content li').width(),
    kind = 0,
    list = [],
    listName = [],
    sendMsg = [],
    comid = '',
    iframeMsg = '',
    isFlag = false;
$(function(){
    $('.row-hoof').css('min-height', h);
    $('.ul-content').css('height', h - 310 + 'px');
    $('.ul-contents').css('height', h - $('#mation').height() - 130 + 'px');
    laydate.render({
        elem: '#date', //指定元素
        showBottom: true,
        btns: ['now', 'confirm'],
        type: 'datetime',
        value: new Date(),
        min: s2
    });
    $.ajax({
        type: 'get',
        url: baseUrls + 'commandStore/list',
        data: {userid: $('#userId').val()},
        beforeSend: function(){
            Loading();
        },
        success: function(response){
            closeLoading();
            if(response.responseCode == '1000'){
                if(response.content.length > 0){
                    for(var i = 0; i < response.content.length; i++){
                        addList.push(response.content[i].infonum);
                        if(response.content[i].cstype == 0){
                            $('.ul-contents').append('<li><span class="cstype">案件</span><span class="firstSpan">'+ response.content[i].infonum +'</span><span class="secondSpan">'+ response.content[i].infoname +'</span><span onclick="cleared(this)"><i class=" fa fa-minus" aria-hidden="true"></i></span></li>');
                        } else{
                            $('.ul-contents').append('<li><span class="cstype">线索</span><span class="firstSpan">'+ response.content[i].infonum +'</span><span class="secondSpan">'+ response.content[i].infoname +'</span><span onclick="cleared(this)"><i class=" fa fa-minus" aria-hidden="true"></i></span></li>');
                        }
                    }
                    $('.title li:eq(1)').addClass('active').removeClass('normal');
                    $('.title li:eq(0)').addClass('normal').removeClass('active');
                    $('.left').hide();
                    $('.right').show();
                    $('.ul-contents').css('height', h - $('#mation').height() - 130 + 'px');
                }
            } else{
                Msg('案件类型获取失败');
            }
        },
        error: function(){
            closeLoading();
            Msg('案件类型获取失败');
        }
    })
    //审核人获取
    $.ajax({
        type: 'get',
        url: baseUrls + 'command/checker',
        data: {userid: $('#userId').val()},
        beforeSend: function(){
            Loading();
        },
        success: function (response) {
            closeLoading();
            if(response.responseCode == '1000'){
                if(response.content.length > 0){
                    $('.audior').html('<option value="">请选择</option>');
                    for(var i = 0; i < response.content.length; i++){
                        $('.audior').append('<option value="'+ response.content[i].USER_ID +'">'+ response.content[i].NAME +'</option>');
                    }
                }
            }else{

            }
        },
        error: function(){
            closeLoading();
        }
    })
    $(window).resize(function(){
        h = $(window).height();
        $('.row-hoof').css('min-height', h);
        $('.model').css('width', $('.input-hoof').outerWidth());
        $('.ul-content').css('height', h - 310 + 'px');
        $('.ul-contents').css('height', h - $('#mation').height() - 130 + 'px');
    })
})
function changekind(item){
    $(item).addClass('active').removeClass('normal');
    $(item).siblings().addClass('normal').removeClass('active');
    if($(item).index() == 0){
        $('.right').hide();
        $('.left').show();
        $('.ul-content').css('height', h - 310 + 'px');
        $('.ul-contents').css('height', h - $('#mation').height() - 130 + 'px');
    } else{
        $('.left').hide();
        $('.right').show();
        $('.num').css({
            opacity: 0,
            filter: 'alpha(opaccity = 0)'
        });
        $('.model').css('width', $('.input-hoof').outerWidth());
        $('.ul-content').css('height', h - 310 + 'px');
        $('.ul-contents').css('height', h - $('#mation').height() - 130 + 'px');
    }
}
function changeTip(item){
    $(item).addClass('liActive').removeClass('liNormal');
    $(item).siblings().addClass('liNormal').removeClass('liActive');
    if($(item).text() == '案件'){
        $('.labelOne-hoof').text('案件编号');
        $('.labelTwo-hoof').text('案件名称');
        $('.list-1').css('display','block');
        $('.list-2').css('display','none');
        kind = 0;
    } else{
        $('.labelOne-hoof').text('线索编号');
        $('.labelTwo-hoof').text('线索名称');
        $('.list-2').css('display','block');
        $('.list-1').css('display','none');
        kind = 1;
    }
}
function getMsg(item){
    var index = $(item).parent().children('.firstSpan').html();
    if(addList.indexOf(index) >= 0){
        Msg('您已添加');
        $(item).parent().addClass('orderLiActive');
    }else {
            var kind = 0;
            if(index.indexOf('A') >= 0){
                kind = 0;
            }
            if(index.indexOf('S') >= 0){
                kind = 1;
            }
            $.ajax({
                type: 'post',
                url: baseUrls + 'commandStore/add',
                data: {userid: $('#userId').val(), infonum: $(item).parent().children(".firstSpan").html(),infoname: $(item).parent().children(".secondSpan").html(),cstype: kind},
                beforeSend: function(){
                    Loading();
                },
                success: function(response){
                    closeLoading();
                    if(response.responseCode == '1000'){
                        addList.push(index);
                        var flyElm = $(item).clone().css('opacity', '0.8');
                        flyElm.css({
                            zIndex: 9000,
                            display: 'block',
                            position: 'absolute',
                            top: $(item).parent().offset().top + 'px',
                            left: $(item).parent().offset().left + 'px',
                            width: $(item).parent().width() + 'px',
                            height: $(item).parent().height() + 'px',
                            color: 'transparent',
                            background: 'rgba(40,56,82,.5)',
                            '-webkit-box-shadow': '0 0 5px #0090e1 inset',
                            '-moz-box-shadow': '0 0 5px #0090e1 inset',
                            '-ms-box-shadow': '0 0 5px #0090e1 inset',
                            '-o-box-shadow': '0 0 5px #0090e1 inset',
                            'box-shadow': '0 0 5px #0090e1 inset'
                        });
                        $('body').append(flyElm);
                        flyElm.animate({
                                top: $('.num').offset().top,
                                left: $('.num').offset().left,
                                width: 2,
                                height: 2
                            },
                            500,
                            function(){
                                $('.num').css({
                                    opacity: 1,
                                    filter: 'alpha(opacity = 1)'
                                })
                                if(kind == 0){
                                    $('.ul-contents').append('<li><span class="cstype">案件</span><span class="firstSpan">'+ $(item).parent().children('.firstSpan').html() +'</span><span class="secondSpan">'+ $(item).parent().children('.secondSpan').html() +'</span><span onclick="cleared(this)"><i class=" fa fa-minus" aria-hidden="true"></i></span></li>');
                                } else{
                                    $('.ul-contents').append('<li><span class="cstype">线索</span><span class="firstSpan">'+ $(item).parent().children('.firstSpan').html() +'</span><span class="secondSpan">'+ $(item).parent().children('.secondSpan').html() +'</span><span onclick="cleared(this)"><i class=" fa fa-minus" aria-hidden="true"></i></span></li>');
                                }
                                flyElm.remove();
                            })
                        $(item).parent().addClass('orderLiActive');
                    } else {
                        closeLoading();
                        Msg('指令添加失败');
                    }
                },
                error: function(){
                    closeLoading();
                    Msg('指令添加失败');
                }
            })
        }
}
function nulls(item){
    var callback;
    if(item != null && item != undefined){
        callback = item;
    } else {
        callback = '无';
    }
    return callback;
}
function nofind(item){
    item.src = 'common/img/nothing.png';
    item.onerror = null;
}
function chooseP(item){
    preventDe(event);
    $(item).toggleClass('pActive');

}
function cleared(item) {
    $.ajax({
        type: 'post',
        url: baseUrls + 'commandStore/delete',
        data: {userid: $('#userId').val(), infonum: $(item).parent().children('.firstSpan').html()},
        beforeSend: function(){
            Loading();
        },
        success: function(response){
            closeLoading();
            if(response.responseCode == '1000'){
                addList.splice($(item).parent().index(),1);
                $(item).parent().remove();
            }else{
                Msg('删除失败');
            }
        },
        error: function(){
            closeLoading();
            Msg('删除失败');
        }
    })
}
function shows(event){
    var e = arguments.callee.caller.arguments[0]||event;
    if (e && e.stopPropagation) {
        e.stopPropagation();
    } else if (window.event) {
        window.event.cancelBubble = true;
    }
    hideIframe();
    $('.model').slideDown();
    $('.model').css('width', $('.input-hoof').outerWidth());

}
function hides(){
    hideIframe();
    $('.model').slideUp();
    if($('.pActive').length > 0){
        $('.input-hoof').val('共' + $('.pActive').length +'名接收人');
    } else{
        $('.input-hoof').val('');
    }
}

function checked(item){
    if($.trim($('.case-hoof').val()).length <= 0 && $.trim($('.name-hoof').val()).length <= 0){
        Msg('输入信息至少填一项');
    } else{
        var num = Math.floor($('#ul-content').height() / 35),
            left = $.trim($('.case-hoof').val()),
            right = $.trim($('.name-hoof').val());
        if(kind == 0){
            $.ajax({
                type: 'get',
                url: baseUrls + 'case/list',
                data: {ajbh: left, ajmc: right,pageIndex: 1, pageSize: num},
                beforeSend: function(){
                    Loading();
                },
                success: function(response){
                    closeLoading();
                    if(response.responseCode == '1000'){
                        if( response.content.list.length > 0){
                            $('#ul-content').html('');
                            for(var i = 0; i < response.content.list.length; i++){
                                $('#ul-content').append('<li><span class="firstSpan">' + response.content.list[i].ajbh + '</span><span class="secondSpan">' + response.content.list[i].ajmc + '</span><span  onclick="getMsg(this)"><i class=" fa fa-plus" aria-hidden="true"></i></span></li>')
                            }
                            $('#demo_pag1').bs_pagination({
                                totalPages: response.content.pages,
                                visiblePageLinks: 10,
                                currentPage: response.content.pageNum,
                                showGoToPage: false,
                                showRowsPerPage: false,
                                showRowsInfo: false,
                                showRowsDefaultInfo: false,
                                navListContainerClass: 'col-xs-12',
                                onChangePage: function (event, data) {
                                    $.ajax({
                                        type: 'get',
                                        url: baseUrls + 'case/list',
                                        data:{ajbh: left, ajmc: right, pageIndex: data.currentPage, pageSize: num},
                                        beforeSend: function(){
                                            Loading();
                                        },
                                        success: function(response){
                                            closeLoading();
                                            if(response.responseCode == '1000'){
                                                $('#ul-content').html('');
                                                for(var i = 0; i < response.content.list.length; i++){
                                                    $('#ul-content').append('<li><span class="firstSpan">' + response.content.list[i].ajbh + '</span><span class="secondSpan">' + response.content.list[i].ajmc + '</span><span  onclick="getMsg(this)"><i class=" fa fa-plus" aria-hidden="true"></i></span></li>')
                                                }
                                            } else{
                                                Msg('查询失败');
                                            }
                                        },
                                        error: function(){
                                            closeLoading();
                                            Msg('查询失败');
                                        }
                                    })
                                }
                            })
                        } else{
                            $('#ul-content').html('');
                            $('#demo_pag1').html('');
                            Msg('查询失败');
                        }
                    } else{
                        Msg('查询失败');
                    }
                },
                error: function(){
                    closeLoading();
                    Msg('查询失败');
                }
            })
        }else{
            $.ajax({
                type: 'get',
                url: baseUrls + 'caseClue/page',
                data: {qzbh: left, qzmc: right,pageIndex: 1, pageSize: num},
                beforeSend: function(){
                    Loading();
                },
                success: function(response){
                    closeLoading();
                    if(response.responseCode == '1000'){
                        if( response.content.list.length > 0){
                            $('#ul-contents').html('');
                            for(var i = 0; i < response.content.list.length; i++){
                                $('#ul-contents').append('<li><span class="firstSpan">' + response.content.list[i].qzbh + '</span><span class="secondSpan">' + response.content.list[i].qzmc + '</span><span  onclick="getMsg(this)"><i class=" fa fa-plus" aria-hidden="true"></i></span></li>')
                            }
                            $('#demo_pag2').bs_pagination({
                                totalPages: response.content.pages,
                                visiblePageLinks: 10,
                                currentPage: response.content.pageNum,
                                showGoToPage: false,
                                showRowsPerPage: false,
                                showRowsInfo: false,
                                showRowsDefaultInfo: false,
                                navListContainerClass: 'col-xs-12',
                                onChangePage: function (event, data) {
                                    $.ajax({
                                        type: 'get',
                                        url: baseUrls + 'caseClue/page',
                                        data:{qzbh: left, qzmc: right, pageIndex: data.currentPage, pageSize: num},
                                        beforeSend: function(){
                                            Loading();
                                        },
                                        success: function(response){
                                            closeLoading();
                                            if(response.responseCode == '1000'){
                                                $('#ul-contents').html('');
                                                for(var i = 0; i < response.content.list.length; i++){
                                                    $('#ul-contents').append('<li><span class="firstSpan">' + response.content.list[i].qzbh + '</span><span class="secondSpan">' + response.content.list[i].qzmc + '</span><span  onclick="getMsg(this)"><i class=" fa fa-plus" aria-hidden="true"></i></span></li>')
                                                }
                                            } else{
                                                Msg('查询失败');
                                            }
                                        },
                                        error: function(){
                                            closeLoading();
                                            Msg('查询失败');
                                        }
                                    })
                                }
                            })
                        } else{
                            $('#ul-contents').html('');
                            $('#demo_pag2').html('');
                            Msg('未查询到结果');
                        }
                    } else{
                        Msg('查询失败');
                    }
                },
                error: function(){
                    closeLoading();
                    Msg('查询失败');
                }
            })
        }
    }
}
function getIndex(p){
    if(p.length > 0){
        var Length = p.length;
        var getMsg = p.substring(0,(Length - 1));
        $('#area').val('共'+ getMsg.split(',').length +'个接收单位');
        if(iframeMsg != p){
            iframeMsg = p;
            $.ajax({
                type: 'get',
                url: baseUrls + 'command/user',
                data: {
                    orgIds: getMsg,
                    userid: $('#userId').val(),
                    sysOrgCode: $('#sysOrgCode').val(),
                    orgLevel: $('#orgLevel').val()
                },
                beforeSend: function(){
                    Loading();
                },
                success: function(response){
                    closeLoading();
                    if(response.responseCode == '1000'){
                        if(response.content.length > 0){
                            $('.model').html('');
                            $('.input-hoof').val('');
                            for(var i = 0; i < response.content.length; i++){
                                $('.model').append('<p onclick="chooseP(this)"><span class="userName choosePLeft" title="' + nulls(response.content[i].name) + '">' + nulls(response.content[i].name) + '</span><span class="choosePCenter"></span><span class="choosePRight" title="'+ nulls(response.content[i].orgName) +'">'+ nulls(response.content[i].orgName) +'</span><input type="hidden" class="userId" value="'+ nulls(response.content[i].userId) +'"><input type="hidden" class="orgName" value="'+ response.content[i].orgName +'"><input type="hidden" class="orgId" value="'+ response.content[i].orgId +'"></p>');
                            };
                        }else{
                            Msg('未查询到接收人');
                        }
                    } else{
                        Msg('未查询到接收人');
                    }
                },
                error: function(){
                    closeLoading();
                    Msg('未查询到接收人');
                }
            })
        }
    }else{
        $('.model').html('');
        $('#area').val('');
    }
}
function sendOrder(){
    var msg = [];
    if($('.input-hoof').val().length > 0 && $.trim($('.comname').val()).length > 0 && $('.audior').find('option:selected').index() > 0){
        for(var i = 0; i < $('.pActive').length; i++){
            msg.push(
                {
                    username: $('.pActive:eq(' + i + ') .userName').html(),
                    userid: $('.pActive:eq(' + i + ') .userId').val(),
                    orgname: $('.pActive:eq(' + i + ') .orgName').val(),
                    orgid: $('.pActive:eq(' + i + ') .orgId').val()
                }
            )
        }
        if(sendMsg.length > 0){
            var formData = new FormData();
            for(var i = 0; i < sendMsg.length; i++){
                formData.append('files', sendMsg[i]);
            }
            for(var i = 0; i < listName.length; i++){
                formData.append('fileNames', listName[i]);
            }
            $.ajax({
                type: 'post',
                url: uploadUrl + 'upload',
                contentType: false,
                processData: false,
                data: formData,
                beforeSend: function(){
                    Loading();
                },
                success: function(response) {
                    closeLoading();
                    if (response.responseCode == '1000') {
                        var fileObj = [];
                        if(response.content.files.length > 0) {
                            var type = '0';
                            for (var i = 0; i < response.content.files.length; i++) {
                                if (response.content.files[i].wllj.indexOf('mp3') > -1 || response.content.files[i].wllj.indexOf('wma') > -1 || response.content.files[i].wllj.indexOf('wav') > -1) {
                                    type = '0';
                                } else if (response.content.files[i].wllj.indexOf('mp4') > -1 || response.content.files[i].wllj.indexOf('rmvb') > -1 || response.content.files[i].wllj.indexOf('avi') > -1) {
                                    type = '1';
                                } else {
                                    type = '2';
                                }
                                fileObj.push({
                                    filetype: type,
                                    filename: response.content.files[i].fileName,
                                    wllj: response.content.files[i].wllj,
                                    gxlj: response.content.files[i].gxlj,
                                    userid: $('#userId').val(),
                                    username: $('#userName').val(),
                                    orgid: $('#orgId').val(),
                                    orgname: $('#orgName').val(),
                                    comid: comid,
                                    originalname: list[i]
                                });
                            }
                        }
                        $.ajax({
                            type: 'post',
                            url: baseUrls + 'command/add',
                            data: {
                                sendid: $('#userId').val(),
                                sendorgname: $('#orgName').val() ,
                                sendname: $('#userName').val(),
                                sendorg: $('#orgId').val(),
                                comname: $.trim($('.comname').val()),
                                comcontent: $.trim($('.comcontent').val()),
                                comlevel: $('.comlevel').val(),
                                limitDay: $('.deadline').val(),
                                users: JSON.stringify(msg),
                                files: JSON.stringify(fileObj),
                                checker: $('.audior').val()
                            },
                            beforeSend: function(){
                                Loading();
                            },
                            success: function(response){
                                closeLoading();
                                if(response.responseCode == '1000'){
                                    Msg('发送成功，请等待审核');
                                    addList = [];
                                    $('.ul-contents').html('');
                                    $('.datalistInput').val('');
                                    $('.input-hoof').val('');
                                    $('.comlevel').find('option:first-child').prop('selected', 'selected');
                                    laydate.render({
                                        elem: '#date', //指定元素
                                        showBottom: true,
                                        btns: ['now', 'confirm'],
                                        type: 'datetime',
                                        value: new Date(),
                                        min: s2
                                    });
                                    $('.comname').val('');
                                    $('.comcontent').val('');
                                    $('.model').html('');
                                    $('#area').val('');
                                    $('#datalist').html('');
                                    $('.audior').find('option:first-child').prop('selected', 'selected');
                                    $('.right').css('display','none');
                                    $('.left').css('display','block');
                                    $('.title li:eq(0)').addClass('active').removeClass('normal');
                                    $('.title li:eq(1)').addClass('normal').removeClass('active');
                                } else{
                                    Msg('发送失败');
                                }
                            },
                            error: function(){
                                closeLoading();
                                Msg('发送失败');
                            }
                        })
                    }else{
                        Msg('发送失败');
                    }
                },
                error: function (){
                    closeLoading();
                    Msg('发送失败');
                }
            })
        }else{
            $.ajax({
                type: 'post',
                url: baseUrls + 'command/add',
                data: {
                    sendid: $('#userId').val(),
                    sendorgname: $('#orgName').val() ,
                    sendname: $('#userName').val(),
                    sendorg: $('#orgId').val(),
                    comname: $.trim($('.comname').val()),
                    comcontent: $.trim($('.comcontent').val()),
                    comlevel: $('.comlevel').val(),
                    limitDay: $('.deadline').val(),
                    users: JSON.stringify(msg),
                    files: '',
                    checker: $('.audior').val()
                },
                beforeSend: function(){
                    Loading();
                },
                success: function(response){
                    closeLoading();
                    if(response.responseCode == '1000'){
                        Msg('发送成功，请等待审核');
                        addList = [];
                        $('.ul-contents').html('');
                        $('.datalistInput').val('');
                        $('.input-hoof').val('');
                        $('.comlevel').find('option:first-child').prop('selected', 'selected');
                        laydate.render({
                            elem: '#date', //指定元素
                            showBottom: true,
                            btns: ['now', 'confirm'],
                            type: 'datetime',
                            value: new Date(),
                            min: s2
                        });
                        $('.comname').val('');
                        $('.comcontent').val('');
                        $('.model').html('');
                        $('#area').val('');
                        $('#datalist').html('');
                        $('.audior').find('option:first-child').prop('selected', 'selected');
                        $('.right').css('display','none');
                        $('.left').css('display','block');
                        $('.title li:eq(0)').addClass('active').removeClass('normal');
                        $('.title li:eq(1)').addClass('normal').removeClass('active');
                    } else{
                        Msg('发送失败');
                    }
                },
                error: function(){
                    closeLoading();
                    Msg('发送失败');
                }
            })
        }
    } else{
        Msg('请先填写必填项');
    }
}
function getFile(node){
    if (node.value) {
        if (node.files && node.files[0]) {
            file = node.files[0];
        } else if (node.files && node.files.item(0)) {
            file = node.files.item(0);
        }
        if(file.size < fileSizes){
            if(list.indexOf(file.name) < 0){
                var newData = new Date();
                list.push(file.name);
                sendMsg.push(file);
                listName.push(addresses + newData.getFullYear() + '/' + (newData.getMonth() + 1) + '/' + newData.getDate() + '/' + comid + '_' + $('#userCode').val() + '_' + newData.getHours() + newData.getMinutes() + newData.getSeconds() + newData.getMilliseconds() + file.name.substr(file.name.lastIndexOf('.')));
                $('.fileLabel').html('<a href="#" class="fileA"><input type="file" name="files" class="fileInput" onchange="getFile(this)"><span>附件上传</span><i class="fa fa-trash-o" aria-hidden="true" onclick="fileDelete(this)"></i></a>');
                $('.fileBox').append('<div class="showFile">'+ file.name +'<i class="fa fa-trash-o" aria-hidden="true" onclick="fileDelete(this)"></i></div>');
            }else{
                $(node).val('');
                Msg('您已选择，如需重复选择请修改名称。');
            }
        }else{
            $(node).val('');
            Msg('您上传的文件超过' + Math.floor((fileSizes / 1024 / 1024)) + 'M。');
        }
    }
}
function fileDelete(item){
    var index = $(item).parent().index();
    $(item).parent().remove();
    list.splice(index,1);
    listName.splice(index,1);
    sendMsg.splice(index,1);
}
function showIframe(){
    $('.model').slideUp();
    if($('.pActive').length > 0){
        $('.input-hoof').val('共' + $('.pActive').length +'名接收人');
    } else{
        $('.input-hoof').val('');
    };
    layer.open({
        title:'接收单位',
        type: 2,
        area: ['495px', '442px'],
        fixed: false, //不固定
        maxmin: false,
        content: 'common/multSel/checkbox_5.html',
        cancel:function(index,layero){
            var p = $(layero).find('iframe')[0].contentWindow.p;
            if(p.length > 0){
                getIndex(p);
            }else{
                Msg('请选择接收单位');
            }
        }
    });
    // isFlag = true;
    // $('.MyIframe_5').css('visibility','visible');
    // $('.MyIframe_5').animate({
    //     height: '402px',
    //     top: '-401px'
    // })
}
function hideIframe(){
    if(isFlag  == true){
        isFlag = false;
        $('.MyIframe_5').css('visibility','hidden');
        $('.MyIframe_5').animate({
            height: 0,
            top: 0
        });
        getIndex();
    }
}
function preventDe(event){
    var e = arguments.callee.caller.arguments[0]||event;
    if (e && e.stopPropagation) {
        e.stopPropagation();
    } else if (window.event) {
        window.event.cancelBubble = true;
    }
}